package com.weblog.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author MaoLin Wang
 * @date 2019/10/616:15
 */
@Component
public class WebFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //得到request上下文
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if(request.getRequestURI().indexOf("security")>0||request.getRequestURI().indexOf("login")>0||request.getRequestURI().indexOf("logout")>0||request.getRequestURI().indexOf("sendCode")>0||request.getRequestURI().indexOf("register")>0){
            return null;
        }
        //得到header
        String header = request.getHeader("Authorization");
        //判断是否有头信息
        if(header!=null &&!"".equals(header)){
            //把头信息继续向下传，因为经过网关头信息会丢失
            context.addZuulRequestHeader("Authorization",header);
        }
        return null;
    }
}
